
import express from 'express';
import http from 'http';
import cluster from 'cluster';
import os from 'os';
import fs from 'fs';
import path from 'path';
import './database/db';
import { initWxTokenAgain } from './database/redis_db';
import { loadPublicPlatforms } from './controllers/wx_token';
import './controllers/mqtt_handler';
import { default as routerDefault } from './routers/index';
import {
    WEB_PROT,
    LOCAL_HTTP_PORT,
    PULL_WXTOKEN_FROM_REDIS,
    NOTIFY_MASTER_RELOAD_PLARFORM,
    NOTIFY_WORKER_RELOAD_PLARFORM
} from './config/config';
import master_wx_token from './controllers/master_wx_token';

// 创建音频存放目录
const uploadsPath = path.join(__dirname, 'web/uploads');
if (!fs.existsSync(uploadsPath)) {
    console.log(uploadsPath)
    fs.mkdirSync(uploadsPath);
}

if (cluster.isMaster) {
    //  http本地服务器,仅做处理微信token操作,使用队列的方式处理
    const app = express();
    const httpServer = http.createServer(app);
    app.get('/wx_token', master_wx_token.weiXinToken);
    httpServer.listen(LOCAL_HTTP_PORT);
    console.log(`Matser running at：${LOCAL_HTTP_PORT},`);

    const numCPUS = os.cpus().length;
    for (let index = 0; index < numCPUS; index++) {
        const wk = cluster.fork();
        // master给worker发送消息
        // wk.send('[master]:' + 'hi worker' + wk.id);
    }
    // 接收消息
    cluster.on('message', function (worker, message, hanlde) {
        console.info(`[master]:from workder[${worker.id}] to master, message;${message}`);
        if (message === NOTIFY_MASTER_RELOAD_PLARFORM) {
            // 重新加载公众号信息
            master_wx_token.reloadInit();
            // 通知对应的工作进程更新公众号信息
            Object.keys(cluster.workers).forEach(function (id) {
                cluster.workers[id].send(NOTIFY_WORKER_RELOAD_PLARFORM);
            });
        }
    })

    // 监听worker退出事件
    cluster.on('exit', function (worker, code, signal) {
        // 一旦检查到有工作进程异常退出必须fork新的Worker,并且发送邮件
        console.info('[master]:' + 'exit worker' + worker.id + ' died');
        const wk = cluster.fork();
        wk.send('[master] ' + 'hi worker' + wk.id);
    });

} else if (cluster.isWorker) {

    process.on('message', function (msg) {
        console.info(`[worker]:from [master] to :${cluster.worker.id}, message:${msg}`);
        if (msg === PULL_WXTOKEN_FROM_REDIS) {
            // 重置内存中的微信token
            initWxTokenAgain(cluster.worker.id);
        } else if (msg === NOTIFY_WORKER_RELOAD_PLARFORM) {
            // 重新加载公众号信息
            loadPublicPlatforms(function () { });
        }
    });

    const port = process.env.PORT || WEB_PROT;
    const app = express();
    routerDefault(app);
    loadPublicPlatforms(() => {
        initWxTokenAgain(cluster.worker.id);
        const httpServer = http.createServer(app);
        httpServer.listen(port);
        console.info(`Woker running at：${port}`);
    });
}









